package com.example.animationplayer.page

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.widget.Toast
import com.example.animationplayer.bean.FileInfo
import com.example.animationplayer.R
import com.example.animationplayer.databinding.ActivityVapAnimationBinding
import com.example.animationplayer.tool.Debugs
import com.example.animationplayer.tool.FileUtil
import com.tencent.qgame.animplayer.AnimConfig
import com.tencent.qgame.animplayer.inter.IAnimListener
import com.tencent.qgame.animplayer.inter.IFetchResource
import com.tencent.qgame.animplayer.inter.OnResourceClickListener
import com.tencent.qgame.animplayer.mix.Resource
import com.tencent.qgame.animplayer.util.ScaleType
import java.io.File

class VapAnimationActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "VapAnimationActivity"
        private const val flowerPosition = 0
        private const val rocketPosition = 1
        private const val announcePosition = 2
        private const val swordPosition = 3
        private const val ohlaLoginPosition = 4

        fun start(context: Context) {
            val starter = Intent(context, VapAnimationActivity::class.java)
            context.startActivity(starter)
        }
    }

    private lateinit var binding: ActivityVapAnimationBinding
    private val vapDir by lazy { getExternalFilesDir(Environment.DIRECTORY_MOVIES)?.absolutePath ?: Environment.getExternalStorageDirectory().path }
    private val fileInfoList: MutableList<FileInfo> by lazy {
        val nameArray = resources.getStringArray(R.array.vap_file_name)
        val md5Array = resources.getStringArray(R.array.vap_file_md5)
        val tempList = mutableListOf<FileInfo>()
        nameArray.forEachIndexed { index, name ->
            tempList.add(FileInfo(name, md5Array[index]))
        }
        tempList
    }
    private var animPosition = 0


    private var animStateListener = object : IAnimListener {
        override fun onFailed(errorType: Int, errorMsg: String?) {
            Debugs.e(TAG, "errorType $errorType msg $errorMsg")
        }

        override fun onVideoComplete() {
            Debugs.i(TAG, "onComplete")
        }

        override fun onVideoDestroy() {
            Debugs.d(TAG, "onVideoDestroy")
        }

        override fun onVideoRender(frameIndex: Int, config: AnimConfig?) {
            Debugs.i(TAG, "onVideoRender frameIndex $frameIndex")
        }

        override fun onVideoStart() {
            Debugs.i(TAG, "onVideoStart")
        }
    }
    private var animFetchListener = object : IFetchResource {
        override fun fetchImage(resource: Resource, result: (Bitmap?) -> Unit) {
            Debugs.d(TAG, "fetch image with key ${resource.tag}")
            if (resource.tag == "user_a_avatar") {
                result.invoke(BitmapFactory.decodeResource(resources, R.mipmap.img_avatar_github))
            } else if (resource.tag == "blind_a_avatar") {
                result.invoke(BitmapFactory.decodeResource(resources, R.mipmap.img_avatar_github))
            } else if (resource.tag == "blind_b_avatar") {
                result.invoke(BitmapFactory.decodeResource(resources, R.mipmap.img_avatar_monster))
            } else if (resource.tag == "[sImg1]") {
                result.invoke(BitmapFactory.decodeResource(resources, R.mipmap.img_avatar_github))
            }
        }

        override fun fetchText(resource: Resource, result: (String?) -> Unit) {
            Debugs.d(TAG, "fetch text with key ${resource.tag}")
            if (resource.tag == "blind_a_name") {
                result.invoke("Cherry")
            } else if (resource.tag == "blind_b_name") {
                result.invoke("Jeff")
            } else if (resource.tag == "[sTxt1]") {
                result.invoke("堕落天使")
            }
        }

        override fun releaseResource(resources: List<Resource>) {
            Debugs.d(TAG, "release Resource")
        }
    }

    private var animClickListener = object : OnResourceClickListener {
        override fun onClick(resource: Resource) {
            Debugs.d(TAG, "click vap resource ${resource.id}")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityVapAnimationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        FileUtil.copyAssetsToStorage(this, vapDir, Array(fileInfoList.size) { fileInfoList[it].fileName }) {
            runOnUiThread {
                Toast.makeText(this, "Copy file Success", Toast.LENGTH_SHORT).show()
            }
        }

        initVapPlayer()

        binding.rgVapAnim.setOnCheckedChangeListener { group, checkedId ->
            animPosition = when (checkedId) {
                binding.rbtnFlower.id -> flowerPosition
                binding.rbtnRocket.id -> rocketPosition
                binding.rbtnAnnounce.id -> announcePosition
                binding.rbtnSword.id -> swordPosition
                binding.rbtnOhlaLogin.id -> ohlaLoginPosition
                else -> 0
            }
            Debugs.d(TAG, "new anim file ${fileInfoList[animPosition]}")
        }

        binding.rgVapScaleType.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                binding.rbtnScaleFitXy.id -> binding.avVap.setScaleType(ScaleType.FIT_XY)
                binding.rbtnScaleFitCenter.id -> binding.avVap.setScaleType(ScaleType.FIT_CENTER)
                binding.rbtnScaleCenterCrop.id -> binding.avVap.setScaleType(ScaleType.CENTER_CROP)
                else -> Debugs.d(TAG, "error checked ")
            }
        }

        binding.rgVapAnim.check(R.id.rbtnFlower)
        binding.rgVapScaleType.check(R.id.rbtnScaleFitCenter)

        binding.btnVapPlay.setOnClickListener {
            val fileInfo = fileInfoList[animPosition]
            val vapFile = File("$vapDir/${fileInfo.fileName}")
            if (FileUtil.getFileMD5(vapFile).equals(fileInfo.md5)) {
                binding.avVap.startPlay(vapFile)
            } else {
                Toast.makeText(this, "File has wrong, check it", Toast.LENGTH_SHORT).show()
            }

        }
        binding.btnVapStop.setOnClickListener {
            binding.avVap.stopPlay()
        }
    }

    private fun initVapPlayer() {
        binding.avVap.apply {
            setAnimListener(animStateListener)
            setFetchResource(animFetchListener)
            setOnResourceClickListener(animClickListener)
        }
    }
}